<template>
  <div class="agent-dashboard">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>商家总数</span>
          </div>
          <div class="statistic-number">{{ statistics.merchantCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>业务员总数</span>
          </div>
          <div class="statistic-number">{{ statistics.salesmanCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>本月订单数</span>
          </div>
          <div class="statistic-number">{{ statistics.orderCount }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>可提现金额</span>
          </div>
          <div class="statistic-number">{{ statistics.withdrawAmount }}</div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>最近订单</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="goToOrderManagement">查看更多</el-button>
          </div>
          <configurable-table
            :columns="recentOrdersColumns"
            :data="recentOrders"
            :loading="ordersLoading"
            :show-index="false"
            :show-pagination="false"
            size="small"
            style="width: 100%">
              <!-- 订单号列 -->
              <template #tradeNo="{ row }">
                <div class="order-info">
                  <i class="el-icon-document"></i>
                  <span class="order-no">{{ row.tradeNo }}</span>
                </div>
              </template>
          </configurable-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>系统概览</span>
          </div>
          <div class="system-overview">
            <p>欢迎使用区域代理管理系统！</p>
            <p>当前登录角色：<strong>区域代理</strong></p>
            <p>系统版本：v1.0.0</p>
            <div class="quick-actions">
              <el-button type="primary" size="small" @click="goToMerchantManagement">商家管理</el-button>
              <el-button type="success" size="small" @click="goToSalesmanManagement">业务员管理</el-button>
              <el-button type="warning" size="small" @click="goToWithdraw">提现管理</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getAgentStatistics, getAccountInfo, getAgentRecentOrders, getOrderPage } from '@/api/aggregation'

export default {
  name: 'AgentDashboard',
  data() {
    return {
      statistics: {
        merchantCount: 0,
        salesmanCount: 0,
        orderCount: 0,
        withdrawAmount: 0
      },
      recentOrders: [],
      ordersLoading: false
    }
  },
  computed: {
    // 最近订单表格列配置
    recentOrdersColumns() {
      return [
        {
          prop: 'tradeNo',
          label: '订单号',
          minWidth: 120,
          slot: 'tradeNo'
        },
        {
          prop: 'merchantName',
          label: '商家',
          minWidth: 100,
          formatter: (row, column, cellValue) => {
            return cellValue || '-'
          }
        },
        {
          prop: 'amount',
          label: '金额',
          minWidth: 80,
          align: 'right',
          formatter: (row, column, cellValue) => {
            return this.formatAmount(cellValue)
          }
        },
        {
          prop: 'createTime',
          label: '时间',
          minWidth: 100,
          formatter: (row, column, cellValue) => {
            return cellValue || '-'
          }
        }
      ]
    }
  },
  mounted() {
    Logger.log('=== 区域代理首页挂载 ===')
    Logger.log('初始数据:', this.statistics, this.recentOrders)
    this.loadAllStatistics()
    this.loadRecentOrders()
  },
  methods: {
    async loadAllStatistics() {
      Logger.log('=== 开始加载所有统计数据 ===')

      try {
        // 获取用户ID
        const userId = this.$store.state.user.id || localStorage.getItem('aggregation-userId')
        Logger.log('当前用户ID:', userId)

        // 只调用可用的接口，移除404的接口
        const [homeStats, accountDetail, orderStats] = await Promise.all([
          getAgentStatistics().catch(error => {
            Logger.error('首页统计失败:', error)
            return { data: { code: 500, data: {} } }
          }),
          userId ? getAccountInfo(userId).catch(error => {
            Logger.error('账户详情失败:', error)
            return { data: { code: 500, data: {} } }
          }) : Promise.resolve({ data: { code: 500, data: {} } }),
          getOrderPage({ pageIndex: 1, pageSize: 1, userType: 4 }).catch(error => {
            Logger.error('订单统计失败:', error)
            return { data: { code: 500, data: {} } }
          })
        ])

        Logger.log('首页统计响应:', homeStats)
        Logger.log('账户详情响应:', accountDetail)
        Logger.log('订单统计响应:', orderStats)

        // 提取数据
        const homeData = homeStats.data?.data || {}
        const accountData = accountDetail.data?.data || {}
        const orderData = orderStats.data?.data || {}

        // 详细调试账户详情接口响应
        Logger.log('=== 账户详情接口完整响应 ===')
        Logger.log('accountDetail完整响应:', accountDetail)
        Logger.log('accountDetail.data:', accountDetail.data)
        Logger.log('accountDetail.data.data:', accountDetail.data?.data)
        Logger.log('accountData:', accountData)
        Logger.log('accountData.balance:', accountData.balance)

        // 合并统计数据，可提现金额直接使用账户详情的balance字段
        this.statistics = {
          merchantCount: homeData.merchantCount || 0,
          salesmanCount: homeData.salesmanCount || 0,
          orderCount: orderData.total || homeData.orderCount || accountData.orderCount || accountData.monthlyOrderCount || accountData.totalOrders || 0,
          withdrawAmount: this.formatAmount(accountData.balance || 0)
        }

        Logger.log('合并后的统计数据:', this.statistics)

        // 调试：专门显示可提现金额的处理过程
        Logger.log('=== 可提现金额调试 ===')
        Logger.log('账户详情balance字段:', accountData.balance)
        Logger.log('最终使用的可提现金额:', accountData.balance || 0)
        Logger.log('格式化后的可提现金额:', this.statistics.withdrawAmount)

      } catch (error) {
        Logger.error('加载统计数据失败:', error)
        this.statistics = {
          merchantCount: 0,
          salesmanCount: 0,
          orderCount: 0,
          withdrawAmount: '¥0.00'
        }
      }
    },

    async loadStatistics() {
      try {
        Logger.log('=== 加载区域代理统计数据 ===')
        const response = await getAgentStatistics()
        Logger.log('统计数据响应:', response)

        if (response.code === 0) {
          Logger.log('统计数据成功:', response.data)
          this.statistics = response.data
        } else {
          Logger.log('统计数据失败，使用默认值:', response.data)
          this.statistics = {
            merchantCount: 0,
            salesmanCount: 0,
            orderCount: 0,
            withdrawAmount: '¥0.00'
          }
        }
      } catch (error) {
        Logger.error('加载统计数据失败:', error)
        Logger.error('错误详情:', error.response?.data)
        this.statistics = {
          merchantCount: 0,
          salesmanCount: 0,
          orderCount: 0,
          withdrawAmount: '¥0.00'
        }
      }
    },

    async loadRecentOrders() {
      this.ordersLoading = true
      try {
        Logger.log('=== 加载区域代理最近订单 ===')
        const response = await getAgentRecentOrders()
        Logger.log('最近订单响应:', response)

        if (response.code === 0) {
          Logger.log('最近订单成功:', response.data)
          // 从分页数据中提取订单列表
          this.recentOrders = response.data.list || []
          Logger.log('提取的订单列表:', this.recentOrders)
          Logger.log('recentOrders数组长度:', this.recentOrders.length)
          Logger.log('recentOrders内容:', JSON.stringify(this.recentOrders))

          // 从订单接口获取总数，更新订单数量
          if (response.data.total !== undefined) {
            this.statistics.orderCount = response.data.total
            Logger.log('从订单接口更新订单总数:', this.statistics.orderCount)
          } else {
            // 如果没有total字段，尝试从其他字段获取
            const total = response.data.totalCount || response.data.count || response.data.recordCount || 0
            this.statistics.orderCount = total
            Logger.log('从其他字段更新订单总数:', total)
          }
        } else {
          Logger.log('最近订单失败，使用空列表:', response.data)
          this.recentOrders = []
        }
      } catch (error) {
        Logger.error('加载最近订单失败:', error)
        Logger.error('错误详情:', error.response?.data)
        this.recentOrders = []

        // 如果最近订单接口失败，尝试直接调用订单分页接口获取总数
        try {
          const orderResponse = await getOrderPage({
            pageIndex: 1,
            pageSize: 1,
            userType: 4 // 区域代理类型
          })
          if (orderResponse.data && orderResponse.data.code === 0) {
            this.statistics.orderCount = orderResponse.data.data.total || 0
            Logger.log('从订单分页接口更新订单总数:', this.statistics.orderCount)
          }
        } catch (orderError) {
          Logger.error('获取订单总数失败:', orderError)
        }
      } finally {
        this.ordersLoading = false
      }
    },

    goToOrderManagement() {
      this.$router.push('/agent/order-management')
    },

    goToMerchantManagement() {
      this.$router.push('/agent/merchant-management')
    },

    goToSalesmanManagement() {
      this.$router.push('/agent/salesman-management')
    },

    goToWithdraw() {
      this.$router.push('/agent/withdraw')
    },

    // 格式化金额
    formatAmount(amount) {
      if (amount === null || amount === undefined) {
        return '¥0.00'
      }

      if (typeof amount === 'number') {
        // 账户详情接口的balance字段是以分为单位，需要除以100
        // 其他接口可能以元为单位，根据数值大小判断
        if (amount >= 100 || amount < 0) {
          // 大于等于100或负数，认为是分为单位，除以100
          return '¥' + (amount / 100).toFixed(2)
        } else {
          // 小于100的正数，认为是元为单位
          return '¥' + amount.toFixed(2)
        }
      } else if (typeof amount === 'string') {
        // 如果已经是格式化过的金额，直接返回
        if (amount.startsWith('¥')) {
          return amount
        }
        // 如果是数字字符串，尝试转换为数字再格式化
        const numAmount = parseFloat(amount)
        if (!isNaN(numAmount)) {
          if (numAmount >= 100 || numAmount < 0) {
            return '¥' + (numAmount / 100).toFixed(2)
          } else {
            return '¥' + numAmount.toFixed(2)
          }
        }
        return '¥0.00'
      }

      return '¥0.00'
    }
  }
}
</script>

<style scoped>
.agent-dashboard {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}


.order-info, .merchant-info, .salesman-info, .product-info, .time-info {
  display: flex;
  align-items: center;
}

.order-info i, .merchant-info i, .salesman-info i, .product-info i, .time-info i {
  margin-right: 5px;
  color: #409eff;
}

.order-no {
  font-weight: bold;
  color: #409eff;
}

.statistic-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  margin-top: 20px;
}

.system-overview {
  padding: 20px;
  line-height: 2;
}

.system-overview p {
  margin: 10px 0;
  font-size: 14px;
}

.quick-actions {
  margin-top: 20px;
}

.quick-actions .el-button {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
